package cn.net.vote.data.filter;

import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.impl.TextCodec;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.util.Base64Utils;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.filter.OncePerRequestFilter;

import cn.net.vote.data.domain.PageData;
import cn.net.vote.util.ConfigUtil;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;

@Component
public class SessionFilter extends OncePerRequestFilter {

	@Override
	protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
			throws ServletException, IOException {
		String authorization = "";
		//request.get
		String methodType = request.getMethod();
		if(RequestMethod.POST.name().equals(methodType)||RequestMethod.OPTIONS.name().equals(methodType)){
			authorization = request.getHeader("Authorization");
		} else  if(RequestMethod.GET.name().equals(methodType)){
			authorization =   request.getParameter("Authorization");
		}
		//logger.info("MethodType:"+methodType);
		logger.debug("Authorization:"+authorization);
		Map<String, Object> extendParams = new HashMap<String, Object>();
		if ("true".equals(ConfigUtil.getString("custom.secureCenter.isValidationToken"))) {
			if (authorization == null && "".equals(authorization)) {
				// throw new
				// WebApplicationException(HttpServletResponse.SC_UNAUTHORIZED);//抛出未认证的错误
			} else {
				// Jws<Claims> claims = Jwts.parser().isSigned(authorization);
				// 如果符合签发格式
				if (Jwts.parser().isSigned(authorization)) {
					String PayloadString = authorization.split("\\.")[1];
					 String jsonStr =new String( Base64Utils.decodeFromString(PayloadString));
					 
					 JSONObject obj = JSON.parseObject(jsonStr);
					 if((!request.getRequestURI().contains("ForClient"))&&("1".equals(obj.getString("utype"))||"2".equals(obj.getString("utype")))){
						 logger.info("后台用户访问，用户等级为管理员或者省级用户，获取查询全部数据权限" );
					 }else{
						 extendParams.put("token_groupcode", obj.getString("groupcode"));
						extendParams.put("token_utype", Integer.valueOf(obj.getString("utype")));
						extendParams.put("token_idcard", obj.getString("idcard")); 
						logger.info("后台用户访问，用户等级为市区科所队用户，权限参数："+extendParams.toString());
					 }
					 
					
					
				}

			}

		}
		ParameterRequestWrapper requestWrapper = new ParameterRequestWrapper(request, extendParams);
		filterChain.doFilter(requestWrapper, response);
	}
}